package rmi.domain;

import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import org.apache.log4j.Logger;

/*
 * If a registry exists on the host with given 
 * properties it will be returned
 *
 */

public class RemoteRegistrySingleton {
	private static Logger log = Logger.getLogger(RemoteRegistrySingleton.class);
	private static Registry reg =null;
	private static String registryHost="";
	private static int port=0;
	
	//return registry
	public static Registry getRemoteRegistry() throws RemoteException{
		readProperties();
		Registry registry = null;

		log.debug("Try get get existing Registry");
		registry = LocateRegistry.getRegistry(registryHost,port);
		if (checkRegistry(registry)){
			return registry;
		}
		else{
			throw new RemoteException();
		}

	}
	//Check if registry is valid
	private static boolean checkRegistry(Registry registry) {
		if (registry != null) {

			try {
				String[] objectsRemote = registry.list();

				for (String o : objectsRemote) {
					log.debug("object available in registry: "+o );
				}
				log.debug("Registry is valid!");
				return true;

			} catch (RemoteException ex) {
				log.debug("Registry is invalid: "+ex.getMessage());
				return false;
			}

		}

		return false;
	}
	//read Propertyfile
	private static void readProperties(){
		java.io.InputStream is = ClassLoader.getSystemResourceAsStream("registry.properties");
		if (is != null) {
			java.util.Properties props = new java.util.Properties();
			try {
				props.load(is);
				registryHost = props.getProperty("registry.host");
				port = Integer.valueOf(props.getProperty("registry.port"));

			} catch (IOException e) {
				System.err.println("No valid Parameters in Propertyfile");
			} finally {
				try {
					is.close();
				} catch (IOException e) {
					log.error("ERROR: Closing I/O Stream!");
				}
			}
		} else {
			System.err.println("Properties file not found!");
		}
	}
}

